﻿using BeetleX.Clients;
using BeetleX;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
namespace Athena.Transport.BeetleX.Packets
{
    using Codec;
    using Message;
    public class BeetleXAthenaClientPacket : IClientPacket, IDisposable
    {
        private readonly IRpcMessageEncoder _rpcMessageEncoder;
        private readonly IRpcMessageDecoder _rpcMessageDecoder;
        private readonly ILoggerFactory _loggerFactory;
        private readonly ILogger _logger;

        public EventClientPacketCompleted Completed { get; set; }


        public BeetleXAthenaClientPacket(IRpcMessageEncoder rpcMessageEncoder, IRpcMessageDecoder rpcMessageDecoder, ILoggerFactory loggerFactory)
        {
            _rpcMessageEncoder = rpcMessageEncoder;
            _rpcMessageDecoder = rpcMessageDecoder;
            _loggerFactory = loggerFactory;
            _logger = _loggerFactory.CreateLogger<BeetleXAthenaClientPacket>();
        }

        public IClientPacket Clone()
        {
            return new BeetleXAthenaClientPacket(_rpcMessageEncoder, _rpcMessageDecoder, _loggerFactory);
        }

        public void Decode(IClient client, Stream stream)
        {
            var pipeStream = StreamHelper.ToPipeStream(stream);
            var content = pipeStream.ReadUTF();
            Completed.Invoke(client, _rpcMessageDecoder.MessageDecoding(content));
        }

        public void Dispose()
        {

        }

        public void Encode(object data, IClient client, Stream stream)
        {
            var pipeStream = StreamHelper.ToPipeStream(stream);
            pipeStream.Write(new Span<byte>(_rpcMessageEncoder.MessageEncoding((RpcTransportMessage)data)));
        }
    }
}
